package cn.concurrent.atomic;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicIntegerFieldUpdater;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @Author: lz
 * @Date: 2018/8/31 16:13
 * @Version 1.0
 */
public class App {
	//属性需要创建newUpdater容器
	// 属性字加volatile关键字
	private static AtomicIntegerFieldUpdater updater = AtomicIntegerFieldUpdater.newUpdater(User.class,"age");

	private static AtomicReference<User> reference = new AtomicReference<>();

	public static void atomicSimple() {
		AtomicInteger atomicInteger = new AtomicInteger(2);
		int i = atomicInteger.addAndGet(3);
		i = atomicInteger.incrementAndGet();
		System.out.println(i);
	}


	public static void main(String[] args) {
		// 简单
//		atomicSimple();
		// 引用
		atomicReference();
		// 属性
		atomicField();

	}

	public static void atomicReference() {
		User user1 = new User("a", 1);
		reference.set(user1);
		User user2 = new User("b", 2);
		User user = reference.getAndSet(user2);
		// 改变了对象
		System.out.println(user);
		// 返回原来的对象
		System.out.println(reference.get());
	}


	public static void atomicField() {
		User user = new User("a", 1);
		int oldValue = updater.getAndAdd(user, 5);
		// 返回对向的属性更改
		System.out.println(oldValue);
		// 没改之前
		System.out.println(updater.get(user));
	}


	static class User {
		private String userName;
		// 引用原子操作
//		private int age;
		// 属性原子操作
		public volatile int age;
		public User(String userName, int age) {
			this.userName = userName;
			this.age = age;
		}

		@Override
		public String toString() {
			return "User{" +
					"userName='" + userName + '\'' +
					", age=" + age +
					'}';
		}

	}

}


